'''
卓越守护百万住院医疗保险（高血压患者专款）
'''

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "卓越守护百万住院医疗保险（高血压患者专款）"

    # 生成产品数据
    def genProductInfo(self):

        plan = {
            # 年龄段
            "year": [str(i) for i in range(18, 55)],
            # 有无社保
            "plan": ["标准版有社保计划", "标准版无社保计划", "经济版有社保计划", "经济版无社保计划"],
            # 保障期限
            "expire": ["1年"]
        }

        for v in product(plan["year"], plan["plan"], plan["expire"]):

            if v[1] == "标准版有社保计划":

                planCode = "H09017"

            elif v[1] == "标准版无社保计划":

                planCode = "H09018"

            elif v[1] == "经济版有社保计划":

                planCode = "H09019"

            else:

                planCode = "H09020"

            # 写入数据库
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], planCode, v[2]))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(v[0], v[1], planCode, v[2]))

    # 执行爬虫
    def requestJson(self, dt=None):

        data = {

            "cityCode": "310100",
            "cityName": "上海市",
            "provinceCode": "310000",
            "provinceName": "上海市",
            "insureBgeinNum": "1",
            "insureEndNum": "30",
            "planCode": "H09",
            "departmentCode": "5",
            "pageInfo": "bralirantTravel",
            "analysisPageInfo": "luck_index",
            "isAgent": "null",
            "ms": "HealthCP_2019_PCmenu",
            "customerClass": "",
            "saleSourceCode": "",
            "customerCod": "",
            "activityCode": "",
            "telMapingId": "",
            "salesRelationId": "71491",
            "insuredNum": "1",
            "isSave": "true",
            "userName": "",
            "insureDays": "365",
            "openCmsUrl": "https: // www.axa.cn",
            "planDefineId": dt["planCode"],
            "firstPlanId": "H09017",
            "pension": "0",
            "isAjax": "1",
            "allYear": "1",
            "isPc": "Y",
            "isDiscount": "",
            "rebate": "",
            "vehicleEcInsureId": "",
            "select_city": "上海市",
            "contractBeginDate": "2020-01-09",
            "contractEndDate": "2021-01-08",
            "insuredBirth": "{year}-01 -01".format( year = str(2019-int(dt["year"]))),
            "requestTypeIsAjax": "1",
        }

        payload = urlencode(data).replace("+", "")

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

        print( r.text )

        if r.status_code == 200 and r.json()["status"] == "success":
            price = Helper.decimalParse(r.json()["data"]["totalActualPremium"])

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }

            self.mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

            print("产品价格更新失败:", dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)



if __name__ == '__main__':
    s = Spider()
    s.genProductInfo()
    s.main()
